package com.ailot.cloud.base.security.utils;


import com.ailot.cloud.base.common.constants.SecurityConstant;
import com.ailot.cloud.base.security.authentication.model.JwtUser;
import lombok.experimental.UtilityClass;
import org.springframework.lang.NonNull;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author litao
 */
@UtilityClass
public class SecurityUtil {
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户信息
     */
    public JwtUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof JwtUser) {
            return (JwtUser) principal;
        }
        return null;
    }

    /**
     * 获取用户信息
     */
    public JwtUser getUser() {
        Authentication authentication = getAuthentication();
        return getUser(authentication);
    }

    /**
     * 获取用权限信息
     */
    public List<String> getAuthorities() {
        Authentication authentication = getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        return authorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());

    }

    /**
     * 登出
     */
    public void logout(@NonNull HttpServletRequest request) {
        new SecurityContextLogoutHandler().logout(request, null, null);
    }

    /**
     * 判断是否内部调用
     * @param request
     * @return
     */
    public boolean isInner(HttpServletRequest request) {
        return request.getHeader(SecurityConstant.FROM) != null
                && request.getHeader(SecurityConstant.FROM).equalsIgnoreCase(SecurityConstant.FROM_IN);
    }

}
